<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        #img {
            position: absolute;
            top: 100px;
            left: 300px;
        }
    </style>
</head>

<body>
    <img src="img/down-0.png" id="img">
    <script>
        var img = document.getElementById("img");
        var index = 0;
         //写公用函数，形参，调用时传入实参
        function fn(value) {
            index++;
            if (index > 4) {
                index = 0;
            }
            img.src = "img/"+value+"-" + index + ".png"
        }
        document.onkeydown = function (e) {
            switch (e.keyCode) {
                case 37:
                    img.style.left = img.offsetLeft - 10 + "px";
                   
                    fn("left");
                    break;
                case 38:
                    img.style.top = img.offsetTop - 10 + "px";
                    fn("up");
                    break;
                case 39:
                    img.style.left = img.offsetLeft + 10 + "px";
                    fn("right");
                    break;
                case 40:
                    img.style.top = img.offsetTop + 10 + "px";
                    fn("down");
                    break;
            }
        }
    </script>
</body>

</html>